<template>
  <div class="equipment">
    <div id="container"></div>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader';
import { getequipmentlist, getTitle } from '@/api/echarts';

let map = null;
let distCluster = null;
let pointSimplifierIns = null;

export default {
  name: 'index',
  props: {
    showPoints: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      lat: null,
      lng: null,
      zoom: 5, // 默认缩放级别
      pointsData: [],
    };
  },
  mounted() {
    this.initMap(); // 初始化地图
  },
  watch: {
    showPoints(newValue) {
      if (newValue) {
        this.initializePointSimplifier().then(() => {
          this.showPointCoordinates();
        });
      } else {
        this.hidePointCoordinates();
      }
    }
  },
  methods: {
    async fetchlnglat() {
      try {
        const title = await getTitle();
        console.log(title, 'title');
        this.lat = parseFloat(title.msg.lat);
        this.lng = parseFloat(title.msg.lng);
        this.zoom = title.msg.zoom;

        if (!isNaN(this.lat) && !isNaN(this.lng) && map) {
          map.setCenter([this.lng, this.lat]);
          map.setZoom(this.zoom);
        } else {
          console.error('无效的经纬度:', this.lat, this.lng, this.zoom);
        }
      } catch (error) {
        console.error('Error fetching title:', error);
      }
    },

    async initializePointSimplifier() {
      if (pointSimplifierIns) {
        // 如果已初始化，直接返回
        return;
      }

      try {
        const { PointSimplifier, utils } = await AMapUI.load(['ui/misc/PointSimplifier', 'lib/utils']);

        if (!PointSimplifier) {
          throw new Error('PointSimplifier is not loaded');
        }

        if (!utils) {
          throw new Error('utils is not loaded');
        }

        pointSimplifierIns = new PointSimplifier({
          map: map,
          autoSetFitView: false,
          zIndex: 110,
          getPosition: function (item) {
            if (!item || !item.lnglat || isNaN(item.lnglat[0]) || isNaN(item.lnglat[1])) {
              return '';
            }
            return item.lnglat;
          },
          getHoverTitle: function (dataItem, idx) {
            return `<div style="height: 12vh;width: 16vw;background-color:#FFFFFF;margin:0;padding:0;z-index:9999999">
              <h2>第${idx + 1}台设备</h2>
              <p>${dataItem.detail}</p>
            </div>`;
          },
          renderOptions: {
            pointStyle: {
              width: 6,
              height: 6,
              fillStyle: 'rgba(153, 0, 153, 0.38)'
            },
            hoverTitleStyle: {
              position: 'top'
            }
          }
        });

        console.log('PointSimplifier initialized successfully.');
      } catch (error) {
        console.error('Failed to initialize PointSimplifier:', error);
      }
    },

    initMap() {
      AMapLoader.load({
        key: "f8c954755588cd09132500151dc4d01c",
        version: "2.0",
        plugins: ['AMap.Scale', 'AMap.Marker', 'AMap.InfoWindow', 'AMap.MarkerCluster'],
        AMapUI: {
          version: '1.1',
          plugins: ['overlay/SimpleMarker']
        }
      }).then((AMap) => {
        map = new AMap.Map("container", {
          viewMode: "2D",
          terrain: false,
          zoom: this.zoom,
          center: [116.397428, 39.90923], // 默认中心点
          mapStyle: 'amap://styles/blue',
        });

        const bounds = new AMap.Bounds(
          new AMap.LngLat(73.502355, 3.837031),
          new AMap.LngLat(135.09567, 53.563624)
        );
        map.setLimitBounds(bounds);

        this.aMapUiLoad(); // 加载 AMap UI 插件
      }).catch(e => {
        console.log(`高德地图加载错误提示${e}`);
      });
    },

    initPage(DistrictCluster, utils) {
      function MyRender(distClusterIns, opts) {
        MyRender.__super__.constructor.apply(this, arguments);
      }

      utils.inherit(MyRender, DistrictCluster.Render.Default);

      utils.extend(MyRender.prototype, {
        drawFeaturePolygons: function (ctx, polygons, styleOptions, feature, dataItems) {
          MyRender.__super__.drawFeaturePolygons.apply(this, arguments);
          if (dataItems.length > 0) {
            this.drawMyLabel(feature, dataItems);
          }
        },
        _initContainter: function () {
          MyRender.__super__._initContainter.apply(this, arguments);
          this._createCanvas('mylabel', this._container);
        },
        drawMyLabel: function (feature, dataItems) {
          var pixelRatio = this.getPixelRatio();
          var containerPos = map.lngLatToContainer(feature.properties.centroid || feature.properties.center);
          var labelCtx = this._getCanvasCxt('mylabel');
          var centerX = containerPos.getX() * pixelRatio,
            centerY = containerPos.getY() * pixelRatio;

          var name = feature.properties.name;
          var count = ' (' + dataItems.length + ')';

          labelCtx.font = 14 * pixelRatio + 'px 微软雅黑';
          var nameMetrics = labelCtx.measureText(name);
          var countMetrics = labelCtx.measureText(count);
          var totalWidth = nameMetrics.width + countMetrics.width;

          var halfTxtWidth = totalWidth / 2;

          var rectWidth = totalWidth + 12 * pixelRatio;
          var rectHeight = 22 * pixelRatio;
          var rectX = centerX - halfTxtWidth - 6 * pixelRatio;
          var rectY = centerY - rectHeight / 2;
          var cornerRadius = 5 * pixelRatio;

          labelCtx.save();
          labelCtx.beginPath();
          labelCtx.moveTo(rectX + cornerRadius, rectY);
          labelCtx.lineTo(rectX + rectWidth - cornerRadius, rectY);
          labelCtx.quadraticCurveTo(rectX + rectWidth, rectY, rectX + rectWidth, rectY + cornerRadius);
          labelCtx.lineTo(rectX + rectWidth, rectY + rectHeight - cornerRadius);
          labelCtx.quadraticCurveTo(rectX + rectWidth, rectY + rectHeight, rectX + rectWidth - cornerRadius, rectY + rectHeight);
          labelCtx.lineTo(rectX + cornerRadius, rectY + rectHeight);
          labelCtx.quadraticCurveTo(rectX, rectY + rectHeight, rectX, rectY + rectHeight - cornerRadius);
          labelCtx.lineTo(rectX, rectY + cornerRadius);
          labelCtx.quadraticCurveTo(rectX, rectY, rectX + cornerRadius, rectY);
          labelCtx.closePath();

          if (feature.properties.level === 'province') {
            labelCtx.fillStyle = '#ADD8E6';
          } else if (feature.properties.level === 'district') {
            labelCtx.fillStyle = '#DDA0DD';
          } else {
            labelCtx.fillStyle = '#FFFFE0';
          }
          labelCtx.fill();

          labelCtx.fillStyle = '#000000';
          labelCtx.textBaseline = 'middle';
          labelCtx.fillText(name, centerX - halfTxtWidth, centerY);

          labelCtx.font = 'bold ' + 14 * pixelRatio + 'px 微软雅黑';
          labelCtx.fillText(count, centerX - halfTxtWidth + nameMetrics.width, centerY);

          labelCtx.restore();
        }
      });

      distCluster = new DistrictCluster({
        zIndex: 100,
        map: map,
        autoSetFitView: false,
        getPosition: function (item) {
          if (!item || !item.lnglat || isNaN(item.lnglat[0]) || isNaN(item.lnglat[1])) {
            return null;
          }
          return item.lnglat;
        },
        renderConstructor: MyRender,
        renderOptions: {
          getClusterMarker: null,
          featureClickToShowSub: true,
          featureStyle: {
            fillStyle: 'rgba(192,192,192,0.5)',
            strokeStyle: 'rgba(0,0,0,0.5)',
            lineWidth: 1,
            hoverOptions: {
              fillStyle: 'rgba(255,255,255,0.01)',
              lineWidth: 2,
              strokeStyle: 'rgb(255,102,0)'
            }
          },
          getFeatureStyle: function (feature, dataItems) {
            if (feature.properties.name === '中国') {
              return {
                fillStyle: 'rgba(192,192,192,0.5)',
                strokeStyle: 'rgba(0,0,0,0.5)',
                lineWidth: 1,
              };
            } else {
              return {
                fillStyle: 'rgba(0, 115, 153, 0.6)',
                strokeStyle: 'rgba(0, 0, 0, 0.5)',
                lineWidth: 1,
              };
            }
          }
        }
      });

      window.distCluster = distCluster;

      this.fetchlnglat(); // 确保地图 UI 组件加载完成后再调用 fetchlnglat
    },

    showPointCoordinates() {
      // 显示点坐标
      if (pointSimplifierIns && this.pointsData.length > 0) {
        pointSimplifierIns.setData(this.pointsData);
      } else {
        console.error('pointSimplifierIns is not initialized or pointsData is empty.');
      }
    },

    hidePointCoordinates() {
      // 隐藏点坐标（清空数据）
      if (pointSimplifierIns) {
        pointSimplifierIns.setData([]);
      }
    },

    aMapUiLoad() {
      AMapUI.load(['ui/geo/DistrictCluster', 'lib/utils'], (DistrictCluster, utils) => {
        if (!DistrictCluster || !utils) {
          console.error('AMapUI plugins are not loaded');
          return;
        }

        this.initPage(DistrictCluster, utils);
      });
    }
  }
};
</script>

<style scoped>
.equipment {
  width: 100%;
  height: 100%;
}
#container {
  width: 100%;
  height: 100%;
}
</style>
